package com.cloud.phone.manager

import android.os.Environment
import android.text.TextUtils
import com.blankj.utilcode.util.FileUtils
import com.cloud.phone.base.BaseApp
import java.io.File

/**
 * @auth: njb
 * @date: 2024/6/26 10:01
 * @desc: 文件管理工具类
 */
object FileManager {

    // 媒体模块根目录
    var SAVE_MEDIA_ROOT_DIR = Environment.DIRECTORY_DCIM

    // 媒体模块存储路径
    private val SAVE_MEDIA_DIR = "$SAVE_MEDIA_ROOT_DIR/cloud-phone"

    // 媒体模块-图片存储路径
    private val SAVE_MEDIA_PHOTO_DIR = "$SAVE_MEDIA_DIR/photo"

    // 媒体模块-相机存储路径
    private val SAVE_MEDIA_VIDEO_DIR = "$SAVE_MEDIA_DIR/video"

    // log 目录
    private const val LOG_DIR = "/log"

    // JPG压缩文件存储地址
    private const val JPG_COMPRESS_DIR = "/compress"

    // apk的安装目录
    private const val APK_DOWNLOAD_PATH = "/apk"

    private val SDCARD_PATH = Environment.getExternalStorageDirectory().path + "/"

    /**
     * 测试apk安装地址
     */
    @JvmField
    var TEST_APK_PATH = "$SDCARD_PATH/$SAVE_MEDIA_ROOT_DIR/cloud-phone.apk"

    @JvmField
    var TEST_IMAGE_PATH = "/${Environment.DIRECTORY_DOWNLOADS}/"

    @JvmField
    var DOWNLOAD_APK_PATH = "/cloud-phone.apk"

    /**
     * 获取文件存储根目录
     */
    fun getStorageRootDir(): String {
        val filePath: File? = BaseApp.app.getExternalFilesDir(null)
        val path: String = if (filePath != null) {
            filePath.absolutePath
        } else {
            BaseApp.app.filesDir.absolutePath
        }
        return path
    }

    /**
     * 获取App私有存储根目录
     */
    fun getAppRootDir(): String {
        val path: String = getStorageRootDir()
        FileUtils.createOrExistsDir(path)
        return path
    }


    /**
     * 获取APK下载目录
     */
    fun getApkDownLoadDir(): String {
        return getSaveDir(APK_DOWNLOAD_PATH)
    }

    /**
     * 获取log存储路径
     */
    fun getLogRootPath(): String {
        return getSaveDir(LOG_DIR)
    }

    /**
     * 获取具体模块存储目录
     */
    fun getSaveDir(directory: String): String {
        var path: String = if (TextUtils.isEmpty(directory) || "/" == directory) {
            ""
        } else if (directory.startsWith("/")) {
            directory
        } else {
            "/$directory"
        }
        path = getAppRootDir() + path
        FileUtils.createOrExistsDir(path)
        return path
    }

    fun appendSlashIfNeeded(path: String): String {
        return if (!path.endsWith("/")) "$path/" else path
    }
}